<?php

class Default_BlogAction extends ProjectBaseAction
{
	public function executeRead(AgaviRequestDataHolder $rd)
	{
		
		$elementsPerPage = 1;
		$page = $rd->getParameter('page', 0);
		$offset = $elementsPerPage*$page; 		      
		        
		$c = new Criteria();
		$maxElements = AfgOMBlogPeer::doCount($c);
		
		$maxPages = ceil($maxElements/$elementsPerPage);
		$this->setAttribute('maxPages',$maxPages);
		
		$c->setOffset($offset);
		$c->setLimit($elementsPerPage);	

		
		$c->addDescendingOrderByColumn(AfgOMBlogPeer::ID);
		$entries = AfgOMBlogPeer::doSelect($c);	 
	
		foreach($entries as $blog) {
			$comArray[] = $blog->toArray();
		}		
		
		if(isset($comArray)) {
			$this->setAttribute('entries',$comArray);
			return 'Success';	
		} else {
			$vm = $this->getContainer()->getValidationManager();
			$vm->setError('noentries','Es gibt leider noch keine Einträge in diesem Blog');
			return 'Error';	
		}	 	
	}


	public function executeWrite(AgaviRequestDataHolder $rd)
	{
		$id = $rd->getParameter('bid');
		if($id>0) {
			// edit exist blog entry
			$c = new Criteria();
			$c->add(AfgOMBlogPeer::ID,$id);
			$afg = AfgOMBlogPeer::doSelectOne($c);
		} else {
			// create new
			$afg = new AfgOMBlog();
		}
		$afg->setDate(strtotime($rd->getParameter('Date')));
		$afg->setTitle($rd->getParameter('Title'));
		$afg->setMessage($rd->getParameter('Message'));
		$afg->setSecret($rd->getParameter('Secret'));
		
		$msgKey = md5($rd->getParameter('Title').$rd->getParameter('Message').$rd->getParameter('Secret'));
		if($msgKey != $this->getContext()->getUser()->getAttribute('lastBlogEntryKey')) {
		    $afg->save();
	        $this->getContext()->getUser()->setAttribute('lastBlogEntryKey',$msgKey);
	        $this->setAttribute('saveBlog',true);
		} else {
			$this->setAttribute('doubleBlog',true);
		}
        $this->setAttribute('resetForm',true);
        
		
		return array('Default',"AdminSuccess");
	}
}
?>